package com.listing.action;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.quartz.SchedulerException;

import com.listing.domain.ListHour;
import com.listing.domain.TimedItems;
import com.listing.service.ListingEngine;
import com.listing.service.ListingService;
import com.taobao.api.domain.Item;

@Results({
	  @Result(name="success", type="redirect", 
			  location="/hour-items", 
			  params={"listHour.dayOfWeek", "${listHour.dayOfWeek}", 
			  	"listHour.hour", "${listHour.hour}",
			  	"expected", "${expected}"}),
	  @Result(name="overflow", type="httpheader", params={"headers.msg", "overflow"})
})
public class WellDistributeAction extends ActionBase{

	private ListHour listHour;
	private boolean expected;
	
	public String execute() throws Exception
	{
		_log.info("hour: " + listHour);
		long userId = getUserId();
		String session = getSessionId();
		String version = getVersion();
		Map<ListHour, TimedItems> hourItemsMap = 
			expected ? ListingService.INSTANCE.getExpectedItems(userId, session) : 
				ListingService.INSTANCE.getHourItems(7, session);
		TimedItems hourItems = hourItemsMap.get(listHour);
		if (hourItems != null)
		{
			List<Item> resultItems = hourItems.getItems();
			if (ListingService.INSTANCE.isOverflow(userId, version, resultItems.size()))
			{
				_log.info("jobs overflow!");
				return "overflow";
			}
			int interval = 60 / resultItems.size();
			_log.info("interval: " + interval);
			ListingEngine engine = new ListingEngine(userId);
			for (int i = 0, n = resultItems.size(); i < n; i++)
			{
				Item item = resultItems.get(i);
				if (!item.getIsVirtual())
				{
					long numIid = item.getNumIid();
					String topSession = getSessionId();
					Calendar cld = Calendar.getInstance();
					cld.setTime(item.getListTime());
					cld.set(Calendar.DAY_OF_WEEK, listHour.getDayOfWeek());
					cld.set(Calendar.HOUR_OF_DAY, listHour.getHour());
					cld.set(Calendar.MINUTE, i * interval);
					Date newListTime = cld.getTime();
					while (newListTime.before(new Date()))
					{
						_log.info("add week period to make time after now.");
						cld.add(Calendar.DATE, 7);
						newListTime = cld.getTime();
					}
					try {
						if (engine.jobExists(numIid))
						{
							engine.remove(numIid);
						}
						engine.list(numIid, newListTime, topSession);
					} catch (SchedulerException e) {
						error(e);
					}
				}
			}
		}
		return SUCCESS;
	}

	public void setListHour(ListHour listHour) {
		this.listHour = listHour;
	}

	public ListHour getListHour() {
		return listHour;
	}

	public void setExpected(boolean expected) {
		this.expected = expected;
	}

	public boolean isExpected() {
		return expected;
	}
}
